package com.example.demo.bizmq;

import com.example.demo.model.Chart;
import com.example.demo.service.ChartService;
import com.example.demo.utils.BusinessException;
import com.example.demo.utils.CommonMethod;
import com.example.demo.utils.ErrorCode;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static com.example.demo.service.impl.AiServiceImpl.*;
import static com.example.demo.service.impl.AiServiceImpl.genGraphData;


@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    // 指定程序监听的消息队列和确认机制
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) int deliveryTag) {
        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)) {
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }
        int chartId = Integer.parseInt(message);
        System.out.println("-----------");
        Chart chart = chartService.getById(chartId);
        int userId=chart.getUserId();
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图表为空");
        }
        // 先修改图表任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        Chart updateChart = new Chart();
        updateChart.setUserId(userId);
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b = chartService.updateById(updateChart);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表执行中状态失败");
            return;
        }

        // 调用 AI,根据不同的图表类型调用不同的AI函数
        String chartType= chart.getChartType();
        String toAImessage = "分析需求：\n";
        toAImessage += chart.getGoal();
        toAImessage += "\n原始数据：\n";
        toAImessage += chart.getRawData();//获得原始数据
        if (chartType == "") {
            toAImessage += "\n图表类型：\n";
            toAImessage += "折线图";
            String result = callWithMessage(toAImessage);
            String code = "", analyse = "";

            String[] strings = result.split("】", 2);
            code = strings[0].replace("【", "");
            analyse = strings[1].replace("【", "");
            code = code.replace("】", "");
            analyse = analyse.replace("】", "");
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setUserId(userId);
            updateChartResult.setGenResult(analyse);
            updateChartResult.setChartData(code);
            updateChartResult.setStatus("succeed");
            chartService.updateById(updateChartResult);
            // 消息确认
            channel.basicAck(deliveryTag, false);
        } else if(chartType.equals("地图")){
            String result=genMapData(toAImessage);
            System.out.println(result);
            String code="",analyse="";
            String[] strings=result.split("【",2);
            code = strings[0];
            code=code.substring(code.indexOf('['));
            code=code.substring(0,code.lastIndexOf("]")+1);
            code = code.replaceAll("(\\w+):", "\"$1\":") // 为属性名添加双引号
                    .replaceAll("'(.*?)'", "\"$1\"") // 为字符串值添加双引号（假设没有其他单引号字符串）
                    .replaceAll(",\\s*]", "]"); // 去除数组最后一个元素后的逗号（如果存在）
            code="{\"tooltip\":{\"trigger\":\"item\"},\"toolbox\":{\"show\":true,\"orient\":\"vertical\",\"left\":\"right\",\"top\":\"center\",\"feature\":{\"dataView\":{\"readOnly\":false},\"restore\":{},\"saveAsImage\":{}}},\"visualMap\":{\"min\":0,\"max\":100,\"text\":[\"High\",\"Low\"],\"realtime\":false,\"calculable\":true,\"inRange\":{\"color\":[\"lightskyblue\",\"yellow\",\"orangered\"]}},\"series\":[{\"type\":\"map\",\"map\":\"china\",\"zoom\":1.5,\"center\":[\"104\",\"36\"],\"roam\":true,\"label\":{\"show\":true},\"itemStyle\":{\"areaColor\":\"#ccc\",\"borderColor\":\"#fff\"},\"visualMap\":{\"min\":0,\"max\":150,\"inRange\":{\"color\":[\"#FFD700\",\"#FF4500\"]},\"show\":false},\"data\":" +
                    code+"}]}";
            System.out.println(code);
            analyse = strings[1].replace("【", "");
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setUserId(userId);
            updateChartResult.setGenResult(analyse);
            updateChartResult.setChartData(code);
            updateChartResult.setStatus("succeed");
            chartService.updateById(updateChartResult);
            channel.basicAck(deliveryTag, false);
        }
        else if(chartType.equals("词云")){
            message=chart.getRawData();
            String result=genWordCloudData(message);
            System.out.println(result);
            String code="",analyse="";
            String[] strings=result.split("【",2);
            code = strings[0];
            code=code.substring(code.indexOf("["));
            code=code.substring(0,code.lastIndexOf("]")+1);
            System.out.println(code);
            code="{\"title\":{\"text\":" +
                    "\"" +chart.getName()+"\""+
                    "},\"tooltip\":{\"show\":true},\"grid\":{\"left\":\"5%\",\"right\":\"5%\",\"bottom\":\"5%\",\"top\":\"5%\",\"containLabel\":true},\"series\":[{\"type\":\"wordCloud\",\"gridSize\":8,\"sizeRange\":[10,80],\"rotationRange\":[0,0],\"rotationStep\":45,\"shape\":\"circle\",\"drawOutOfBound\":false,\"layoutAnimation\":true,\"left\":\"center\",\"top\":\"center\",\"textStyle\":{\"fontFamily\":\"sans-serif\"},\"data\":" +
                    code +
                    ",\"emphasis\":{\"focus\":\"self\",\"textStyle\":{\"fontSize\":20}}}]}";
            analyse=strings[1];
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setUserId(userId);
            updateChartResult.setGenResult(analyse);
            updateChartResult.setChartData(code);
            updateChartResult.setStatus("succeed");
            chartService.updateById(updateChartResult);
            // 消息确认
            channel.basicAck(deliveryTag, false);
        }
        else if(chartType.equals("关系图")){
            message=chart.getRawData();
            String result=genGraphData(message);
            System.out.println(result);
            String code="",analyse="";
            String[] strings=result.split("【",2);
            code = strings[0];
            code=code.substring(code.indexOf("["));
            code=code.substring(0,code.lastIndexOf("]")+1);
            code="{\"title\":{\"text\":" +
                    "\"" +chart.getName()+"\""+
                    ",\"subtext\":\""+chart.getName()+"\"" +
                    ",\"top\":\"bottom\",\"left\":\"right\"},\"tooltip\":{},\"legend\":[{\"data\":" +
                    "[]}]," +
                    "\"animationDuration\":1500,\"animationEasingUpdate\":\"quinticInOut\",\"series\":[{\"name\":\"Les Miserables\",\"type\":\"graph\",\"legendHoverLink\":\"false\",\"layout\":\"none\"," +
                    "\"data\":"+code +
                    ",\"roam\":\"true\",\"label\":{\"position\":\"right\",\"formatter\":\"{b}\"},\"lineStyle\":{\"color\":\"source\",\"curveness\":0.3},\"emphasis\":{\"focus\":\"adjacency\",\"lineStyle\":{\"width\":10}}}]}";
            analyse=strings[1];
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setUserId(userId);
            updateChartResult.setGenResult(analyse);
            updateChartResult.setChartData(code);
            updateChartResult.setStatus("succeed");
            chartService.updateById(updateChartResult);
            // 消息确认
            channel.basicAck(deliveryTag, false);
        }
        else {
            toAImessage += "\n图表类型：\n";
            toAImessage += chartType;
            String result = callWithMessage(toAImessage);
            String code = "", analyse = "";

            String[] strings = result.split("】", 2);
            code = strings[0].replace("【", "");
            analyse = strings[1].replace("【", "");
            code = code.replace("】", "");
            analyse = analyse.replace("】", "");
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setUserId(userId);
            updateChartResult.setGenResult(analyse);
            updateChartResult.setChartData(code);
            updateChartResult.setStatus("succeed");
            chartService.updateById(updateChartResult);
            // 消息确认
            channel.basicAck(deliveryTag, false);
        }

    }



    private void handleChartUpdateError(int chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage("execMessage");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }

}
